﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using HousingInfo.Library;
using System.IO;

namespace Admin.Admin
{
    public partial class Users : System.Web.UI.Page
    {
        private static UserBO userbo;
        private static string _fileImageName;
        protected void Page_Load(object sender, EventArgs e)
        {

            //if ((Session["LOGIN"] == null) || (int)Session["ROLES"] != 1)
            //{
            //    Response.Redirect("Login.aspx");
            //}
            if (!IsPostBack)
            {
                listRoles.DataSource = RoleInfo.GetRoleInfo();
                listRoles.DataBind();
                dropdownlistQuestion.DataSource = QuestionInfo.GetQuestionInfo();
                dropdownlistQuestion.DataBind();

                string mode = Request.QueryString["Mode"];
                //Mode Add
                //if (mode == "1")
                //{
                //    btnUpdate.Visible = false;
                //    btnDelete.Visible = false;
                //    txtusername.ReadOnly = false;
                //    LabelRegisterDate.Visible = false;
                //    txtregisterdate.Visible = false;
                //    listRoles.SelectedIndex = 1;
                //    PanelActions.Visible = true;
                //    //PanelDasboard.Visible = false;
                //    lbHeaderActions.Text = "Thêm thành viên";
                //    GridView1.Columns[0].Visible = false;
                //}
                //else //Mode Update
                //{
                //    btnAdd.Visible = false;
                //    txtusername.Enabled = false;
                //    txtpassword.Enabled = false;
                //    lbHeaderActions.Text = "Sửa thông tin thành viên";
                //}
            }

        }
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string username = GridView1.SelectedRow.Cells[2].Text.ToString();
            userbo = UserBO.GetUserBO(username);
            txtusername.Text = userbo.UserName;
            txtusername.Enabled = true;
            txtusername.ReadOnly = true;
            pn_password.Visible = false;
            listRoles.SelectedValue = userbo.RoleID.ToString();
            txtfullname.Text = userbo.FullName;
            txtbirth.Text = Convert.ToDateTime(userbo.BirthDay).ToString("dd/MM/yyyy");
            txtemail.Text = userbo.Email;
            txtnickyahoo.Text = userbo.NickYahoo;
            txtnickskyer.Text = userbo.NickSkyper;
            txttelephone.Text = userbo.TelePhone;
            txtmobiphone.Text = userbo.MobilePhone;
            txtaddress.Text = userbo.Address;
            cbbProvincy.SelectedValue = userbo.City;
            txturlwebsite.Text = userbo.UrlWebsite;
            txtregisterdate.Text = userbo.RegisterDate.Value.ToString("dd/MM/yyyy");
            txtregisterdate.Enabled = true;
            txtregisterdate.ReadOnly = true;
            dropdownlistQuestion.SelectedValue = userbo.QuestionID.ToString();
            txtAnswerQuestion.Text = userbo.AnswerQuestion;
            btnAdd.Visible = false;
            btnUpdate.Visible = true;
            btnDelete.Visible = true;
            pn_before_lock.Visible = true;
            pn_droplist.Visible = false;
            if (userbo.Islock == true)
            {
                pn_lock.Visible = true;
                txtlockdate.Text = userbo.LockDate.Value.ToString("dd/MM/yyyy");
                txtlockdate.Enabled = true;
                txtlockdate.ReadOnly = true;
                txtunlockdate.Text = userbo.UnlockDate.Value.ToString("dd/MM/yyyy");
                txtunlockdate.Enabled = true;
                txtunlockdate.ReadOnly = true;
                lblthongbaokhoa.Text = "Tài khoản đang bị khoá";
                lbtkhoa.Text = "Mở Khoá";
            }
            else
            {
                pn_lock.Visible = false;
                lblthongbaokhoa.Text = "";
                lbtkhoa.Text = "Khoá Người Dùng Này";
            }
            //isActive.Checked = userbo.IsActive;
            message.Text = "";
            if (PanelActions.Visible == false)
                PanelActions.Visible = true;
            messagedelete.Text = "";
            if (userbo.Avatar != "")
            {
                string filePath = HttpContext.Current.Server.MapPath("~/TotalUpload/UserAvatar/" + userbo.Avatar);
                FileUpload_Avatar.Visible = false;
                txtavatar.Visible = true;
                txtavatar.Text = filePath;
                txtavatar.ReadOnly = true;
                btnchangeavatar.Visible = true;
            }
            else
            {
                FileUpload_Avatar.Visible = true;
                txtavatar.Visible = false;
                btnchangeavatar.Visible = false;
            }

        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {

            message.Text = "";
            userbo = UserBO.GetUserBO(txtusername.Text);
            userbo.FullName = txtfullname.Text;
          //  userbo.RoleID = listRoles.SelectedIndex + 1;
            try
            {
                userbo.BirthDay = Convert.ToDateTime(txtbirth.Text);
            }
            catch
            {
                var convert = txtbirth.Text.Split('/');
                userbo.BirthDay = Convert.ToDateTime(convert[1].ToString() + "/" + convert[0].ToString() + "/" + convert[2].ToString());
            }
            userbo.Email = txtemail.Text;
            userbo.NickYahoo = txtnickyahoo.Text;
            userbo.NickSkyper = txtnickskyer.Text;
            userbo.TelePhone = txttelephone.Text;
            userbo.MobilePhone = txtmobiphone.Text;
            userbo.Address = txtaddress.Text;
           // userbo.City = cbbProvincy.SelectedValue.ToString();
            userbo.UrlWebsite = txturlwebsite.Text;
           // userbo.QuestionID = int.Parse(dropdownlistQuestion.SelectedValue);
            userbo.AnswerQuestion = txtAnswerQuestion.Text;
            if (pn_droplist.Visible == false && pn_lock.Visible == false)
            {
                userbo.Islock = false;
                userbo.LockDate = null;
                userbo.UnlockDate = null;
            }
            else if (pn_droplist.Visible == true)
            {
                userbo.Islock = true;
                userbo.LockDate = DateTime.Now;
                userbo.UnlockDate = DateTime.Now.AddDays(double.Parse(dlsongaykhoa.SelectedValue));
            }
            try
            {
                userbo.Save();
                btnhuy.Visible = false;
                message.Text = "Cập nhật thành công !";
            }
            catch
            {
                message.Text = "Cập nhật thất bại !";
            }

            GridView1.DataBind();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {

            if (NewsHouseBOList.CheckNewsHouseinAreaDetail(null, txtusername.Text, null))
            {

                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Bạn phải xóa những tin do người dùng này đăng trước !!! !!!')", true);

                return;
            }

            try
            {
                UserBO.DeleteUserBO(txtusername.Text);
                messagedelete.Text = "Xóa thành công !";
                PanelActions.Visible = false;
            }
            catch
            {
                message.Text = "Xóa thất bại !";
                return;
            }
            GridView1.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
             if (!UserBO.CheckUserNameExist(txtusername.Text))
            {
                userbo = UserBO.NewUserBO(txtusername.Text);
                userbo.FullName = txtfullname.Text;
                //userbo.BirthDay = txtbirth.Text;
                DateTime dateti;
                dateti = Convert.ToDateTime(txtbirth.Text);
                try
                {
                    userbo.BirthDay = Convert.ToDateTime(dateti.ToString("dd/MM/yyyy"));
                }
                catch
                {
                    userbo.BirthDay = Convert.ToDateTime(dateti.ToString("MM/dd/yyyy"));
                }
                userbo.Email = txtemail.Text;
                userbo.Password = UserBO.encryptData(txtpassword.Text);
                userbo.RoleID = Convert.ToInt32(listRoles.SelectedValue);
                userbo.NickYahoo = txtnickyahoo.Text;
                userbo.NickSkyper = txtnickskyer.Text;
                userbo.TelePhone = txttelephone.Text;
                userbo.MobilePhone = txtmobiphone.Text;
                userbo.Address = txtaddress.Text;
                userbo.City = cbbProvincy.SelectedValue;
                userbo.UrlWebsite = txturlwebsite.Text;
                userbo.IsActive = true;
                userbo.Islock = false;
                userbo.RegisterDate = DateTime.Now;
                userbo.QuestionID = int.Parse(dropdownlistQuestion.SelectedValue);
                userbo.AnswerQuestion = txtAnswerQuestion.Text;
                //if (upload_one_image.FileName.Length > 0)
                //{
                //    postImage(upload_one_image, "", "");
                //}
                if(FileUpload_Avatar.FileName.Length > 0)
                {
                    postImage(FileUpload_Avatar);
                }
                else userbo.Avatar = "";
                try
                {
                    userbo.Save();
                    message.Text = "Thêm thành công !";
                    GridView1.DataBind();
                    resetControls();
                }
                catch
                {
                    message.Text = "Thêm thất bại !";
                }
            }

            else
            {
                message.Text = "Tài khoản đã tồn tại !";
            }
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            
        }

        protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
           //// Response.Write("<script>alert('Hello')</script>");
        }

        private void resetControls()
        {
            txtusername.Text = "";
            txtpassword.Text = "";
            txtfullname.Text = "";
            txtbirth.Text = "";
            FileUpload_Avatar.Visible = true;
            txtnickyahoo.Text = "";
            txtnickskyer.Text = "";
            txttelephone.Text = "";
            txtmobiphone.Text = "";
            txturlwebsite.Text = "http://";
            txtaddress.Text = "";
            txtAnswerQuestion.Text = "";
            //dropdownlistQuestion.DataSource = QuestionInfo.GetQuestionInfo();
        }

        private void postImage(FileUpload filename)
        {
            try
            {
                if (filename.HasFile)
                {
                    if (filename.FileBytes.Length < 512000)
                    {
                        _fileImageName = filename.FileName.Replace(" ", "_");

                        string formatFile = Path.GetExtension(_fileImageName);
                        //kiem tra dinh dang cho phep upload
                        if (formatFile.Equals(".jpg") || formatFile.Equals(".gif") || formatFile.Equals(".png") || formatFile.Equals(".JPG") || formatFile.Equals(".GIF") || formatFile.Equals(".PNG"))
                        {
                            //kiem tra file da ton tai
                            string filePath = HttpContext.Current.Server.MapPath("~/TotalUpload/UserAvatar/" + _fileImageName);
                            if (File.Exists(filePath))
                            {
                                //neu ton tai thi doi ten
                                _fileImageName = ImageFileName(_fileImageName);
                            }
                            //thuc hien luu file
                            try
                            {
                                filename.SaveAs(Server.MapPath("~/TotalUpload/UserAvatar/" + _fileImageName));
                                //deleteExitsImage(txtlink.Text);
                                //txtlink.Text = _fileImageName;
                                try
                                {
                                    userbo.Avatar = _fileImageName;
                                }
                                catch
                                {
                                    userbo.Avatar = "";
                                }
                            }
                            catch (Exception)
                            {
                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Có một số vấn đề xả ra trong khi lưu. Xin hay thử lại.')", true);
                                return;
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chỉ được upload các định dạng ảnh (.jpg , .gif, .png)')", true);
                            return;
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Kích thước ảnh không quá 500Kb.')", true);
                        return;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chưa chọn hỉnh ảnh đại diện. !')", true);
                    return;
                }
            }
            catch { }
        }

        private static string ImageFileName(string fileName)
        {
            Random r = new Random();
            return r.Next(0, 10000).ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + fileName;
        }

        private void deleteExitsImage(string filedelete)
        {
            try
            {
                var pathFileImage = Server.MapPath("~/TotalUpload/UserAvatar/" + filedelete);
                FileInfo fileInfo;
                if (File.Exists(pathFileImage))
                {
                    fileInfo = new FileInfo(pathFileImage);
                    fileInfo.Delete();
                }
            }
            catch
            {
            }
        }

        protected void btnchangeavatar_Click(object sender, EventArgs e)
        {
            txtavatar.Visible = false;
            FileUpload_Avatar.Visible = true;
            btnhuy.Visible = true;
            btnchangeavatar.Visible = false;
            btnUpdate.Focus();
        }

        protected void btnhuy_Click(object sender, EventArgs e)
        {
            try
            {
                FileUpload_Avatar.Visible = false;
                btnchangeavatar.Visible = true;
                txtavatar.Visible = true;
                btnhuy.Visible = false;
                btnUpdate.Focus();
            }
            catch { }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    string strScript = "SelectDeSelectHeader(" + ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).ClientID + ");";
                    ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).Attributes.Add("onclick", strScript);
                }
            }
            catch
            {
                //report error
            }  
        }

        protected void btnadduser_Click(object sender, EventArgs e)
        {
            resetControls();
            btnUpdate.Visible = false;
            btnDelete.Visible = false;
            btnAdd.Visible = true;
            pn_lock.Visible = false;
            txtusername.ReadOnly = false;
            txtpassword.Visible = true;
            LabelRegisterDate.Visible = false;
            txtregisterdate.Visible = false;
            listRoles.SelectedIndex = 1;
            PanelActions.Visible = true;
            //PanelDasboard.Visible = false;
            lbHeaderActions.Text = "Thêm thành viên";
            pn_password.Visible = true;
            //GridView1.Columns[0].Visible = false;
            txtavatar.Visible = false;
            btnchangeavatar.Visible = false;
            FileUpload_Avatar.Visible = true;
            btnhuy.Visible = false;
        }

        protected void btndeleteuser_Click(object sender, EventArgs e)
        {
            bool test = false;
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
                if (chkSel.Checked == true)
                {
                    try
                    {
                        test = true;
                        string username = gvRow.Cells[2].Text;
                        UserBO.DeleteUserBO(username);
                    }
                    catch
                    {
                        messagedelete.Text = "Xóa thất bại. Thành viên này hiện đang đăng bài viết.";
                        return;
                    }
                }
            }
            if (test == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn thông tin cần xóa !!!')", true);
                return;
            }
            else
            {

                GridView1.DataBind();
                messagedelete.Text = "Xóa thành công! ";
            }
        }

        protected void btncancel_Click(object sender, EventArgs e)
        {
            PanelActions.Visible = false;
        }
        protected void lbtkhoa_Click(object sender, EventArgs e)
        {
            if (lbtkhoa.Text == "Khoá Người Dùng Này")
            {
                pn_lock.Visible = false;
                pn_droplist.Visible = true;
                btnUpdate.Focus();
            }
            else if (lbtkhoa.Text == "Mở Khoá")
            {
                lbtkhoa.Text = "Khoá Người Dùng Này";
                lblthongbaokhoa.Text = "Mở khoá thành công";
                pn_lock.Visible = false;
                btnUpdate.Focus();
            }
        }

        protected void lbttatca_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListNewsHouseByUser.aspx?user=" + txtusername.Text + "&type=all");
        }

        protected void lbttraphi_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListNewsHouseByUser.aspx?user=" + txtusername.Text + "&type=premium");
        }

        protected void lbtdangdang_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListNewsHouseByUser.aspx?user=" + txtusername.Text + "&type=posting");
        }

        protected void lbtchoduyet_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListNewsHouseByUser.aspx?user=" + txtusername.Text + "&type=approve");
        }

        protected void lbtdaluu_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListNewsHouseByUser.aspx?user=" + txtusername.Text + "&type=save");
        }

        protected void lbthethan_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListNewsHouseByUser.aspx?user=" + txtusername.Text + "&type=expridate");
        }
    }
}
